package com.lhkk.inventoryvehicle

import android.app.Application
import android.content.Context
import com.cj.mvvmlib.base.BaseApp
import com.lhkk.inventoryvehicle.common.GlobalVariables
import com.lhkk.inventoryvehicle.common.LogFileUtils


class AppContext : Application() {

    override fun onCreate() {
        super.onCreate()
        appContext = this //程序崩溃异常捕获并自动重启
        Thread.setDefaultUncaughtExceptionHandler(restartHandler) //初始化基础模块上下文
        BaseApp.initContext(this)
        createImageFolder()
        LogFileUtils.init(this)
    }

    companion object {
        private lateinit var appContext: AppContext

        @Synchronized
        fun getContext(): Context {
            return appContext
        }
    }

    private val restartHandler =
        Thread.UncaughtExceptionHandler { _: Thread?, e: Throwable -> //        LogFileUtils.writeTxtToFile("程序异常：$e")

            //        val intent = Intent(this, MainActivity::class.java) //重启应用，得使用PendingIntent
            //        val restartIntent = PendingIntent.getActivity(this,
            //            0,
            //            intent,
            //            PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE)
            //        val mAlarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
            //        mAlarmManager[AlarmManager.RTC, System.currentTimeMillis() + 2000] =
            //            restartIntent // 2秒钟后重启应用
            //        AppManager.getAppManager().finishAllActivity() //退出程序
            //        Process.killProcess(Process.myPid()) //结束当前进程

        }

    /**
     * 创建图片保存文件夹
     */
    private fun createImageFolder() {
        val imagePath = getExternalFilesDir("image")
        val logPath = getExternalFilesDir("log")
        GlobalVariables.setImagePath(imagePath?.absolutePath ?: "")
        GlobalVariables.setLogPath(logPath?.absolutePath ?: "")
    }
}